/**
 * Copyright (C) 2015-2016 Guangzhou Xunhong Network Technology Co., Ltd. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jxccp.ui.view;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.core.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.Toast;

import com.jxccp.im.chat.common.message.ImageMessage;
import com.jxccp.im.chat.manager.JXImManager;
import com.jxccp.im.util.log.JXLog;
import com.jxccp.ui.JXConstants;
import com.jxccp.ui.JXUiHelper;
import com.jxccp.ui.R;
import com.jxccp.ui.listeners.JXChatGeneralCallback;
import com.jxccp.ui.utils.JXNotificationUtils;
import com.jxccp.ui.utils.JXPermissionUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class JXChatUIActivity extends JXBaseFragmentActivity implements JXChatGeneralCallback,JXPermissionUtil.OnPermissionCallback{

    public static final String TAG = "chat";

    private JXChatFragment chatFragment;

    private List<Integer> functionImages = new ArrayList<>();

    private List<String> functionName =new ArrayList<>();

    private GetQuickQuestionTask getQuickQuestionTask;

    private JXPermissionUtil mJXPermissionUtil;

    private int permissionRequestCode = 1;

    private boolean reStart = false;

    private String reStartKey;

    private String reStartSuboryId;

    private String reStartTitleKey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jx_activity_chat);
        // 聊天界面加载JXChatFragment
        chatFragment = new JXChatFragment();
        Bundle args = new Bundle();
        // 设置相应属性,CHAT_KEY为聊天的对象,访客这里为技能组的ID，CHAT_SKILLS_DISPLAYNAME为技能组的昵称
        args.putInt(JXConstants.EXTRA_CHAT_TYPE, getIntent().getIntExtra(JXConstants.EXTRA_CHAT_TYPE, JXChatView.CHATTYPE_CUSTOMER_SERVICE));
        args.putString(JXConstants.EXTRA_CHAT_KEY, getIntent().getStringExtra(JXConstants.EXTRA_CHAT_KEY));
        args.putString(JXConstants.EXTRA_CHAT_TITLE_KEY, getIntent().getStringExtra(JXConstants.EXTRA_CHAT_TITLE_KEY));
        // 扩展信息
        args.putString(JXConstants.EXTRA_CHAT_EXTEND_DATE, getIntent().getStringExtra(JXConstants.EXTRA_CHAT_EXTEND_DATE));

        String suborgId = getIntent().getStringExtra(JXConstants.EXTRA_SUBORG_ID_KEY);
        if (!TextUtils.isEmpty(suborgId)){
            //从通知栏直接进入区分多组织
            JXUiHelper.getInstance().setSuborgId(suborgId);
            JXImManager.McsUser.getInstance().setSuborgId(suborgId);
        }

        configFuntionRes();

        chatFragment.setArguments(args);

        getSupportFragmentManager().beginTransaction().replace(R.id.fl_container, chatFragment, TAG)
                .commit();

        chatFragment.configFunctionPanel(functionImages, functionName);

        chatFragment.setJXChatGeneralCallback(this);

        JXUiHelper.getInstance().setChatPage(true);
        mJXPermissionUtil = new JXPermissionUtil();
    }

    private void configFuntionRes() {
        // 聊天界面功能面板的图片资源的id,这里数组的顺序与下面配置的string的顺序对应
        if (JXImManager.McsUser.getInstance().canSendPic()){
            functionImages.add(R.drawable.jx_bg_image_click);
            functionImages.add(R.drawable.jx_bg_take_photo_click);
            functionName.add(getString(R.string.jx_image));
            functionName.add(getString(R.string.jx_take_photo));
        }
        if (JXImManager.McsUser.getInstance().canSendVideo()) {
            functionImages.add(R.drawable.jx_bg_function_video);
            functionName.add(getString(R.string.jx_videomsg));
        }

        if (JXImManager.McsUser.getInstance().isVisitorSatisfyOpen()) {
            functionImages.add(R.drawable.jx_bg_evaluate_click);
            functionName.add(getString(R.string.jx_satisfaction_evaluate));
        }

        if (!JXImManager.Config.getInstance().isHKBN()){
            if (JXUiHelper.getInstance().isUseCommonQuestion()){
                functionImages.add(R.drawable.jx_bg_quick_question_click);
                functionName.add(getString(R.string.jx_common_question));
            }else {
                getQuickQuestionTask = new GetQuickQuestionTask(this);
                getQuickQuestionTask.execute();
            }
        }

        if (JXImManager.McsUser.getInstance().canSendLocation()) {
            functionImages.add(R.drawable.jx_bg_location_click);
            functionName.add(getString(R.string.jx_location));
        }

        if (JXImManager.Config.getInstance().robotSatisfyEnable()){
            functionImages.add(R.drawable.jx_bg_advice);
            functionName.add(getString(R.string.jx_online_advice));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        JXNotificationUtils.cancelAllNotifty();
        JXUiHelper.getInstance().setChatPage(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getQuickQuestionTask != null){
            getQuickQuestionTask.cancel(true);
        }
        mJXPermissionUtil = null;
        if (reStart){
            Intent initIntent = new Intent();
            initIntent.setClass(this, JXInitActivity.class);
            initIntent.putExtra(JXConstants.EXTRA_CHAT_KEY, reStartKey);
            initIntent.putExtra(JXConstants.EXTRA_SUBORG_ID_KEY,reStartSuboryId);
            initIntent.putExtra(JXConstants.EXTRA_CHAT_TITLE_KEY,reStartTitleKey);
            startActivity(initIntent);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        JXUiHelper.getInstance().setChatPage(false);
    }

    public boolean isVisiable(){
        if(chatFragment != null){
            return chatFragment.isVisiable;
        }
        return false;
    }

    /**
     * 当前界面是否为消息中心界面
     * @return
     */
    public boolean isMessagebox(){
        if(messageBoxFragment != null){
            FragmentManager fragmentManager = getSupportFragmentManager();
            Fragment fragment = fragmentManager.findFragmentByTag("messageBox");
            if(fragment != null){
                return true;
            }
        }
        if(chatFragment != null){
            return chatFragment.isMessagebox();
        }
        return false;
    }

    @Override
    public void onFunctionItemClick(int position, int drawableResId) {
        if (drawableResId == R.drawable.jx_bg_image_click) {
            permissionRequestCode = R.drawable.jx_bg_image_click;
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ){
                String[] permissions = new String[]{ Manifest.permission.WRITE_EXTERNAL_STORAGE};
                mJXPermissionUtil.requestPermissions(this, permissionRequestCode, permissions, this);
            }else{
                onGranted();
            }
        } else if (drawableResId == R.drawable.jx_bg_take_photo_click) {
            permissionRequestCode = R.drawable.jx_bg_take_photo_click;
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ){
                String[] permissions = new String[]{ Manifest.permission.CAMERA};
                mJXPermissionUtil.requestPermissions(this, permissionRequestCode, permissions, this);
            }else{
                takePhoto();
            }
        } else if (drawableResId == R.drawable.jx_bg_function_video) {
            chatFragment.navToVideo();
        } else if (drawableResId == R.drawable.jx_bg_evaluate_click) {
            chatFragment.chatPresenter.fetchEvaluateInfo(null,false);
        } else if (drawableResId == R.drawable.jx_bg_quick_question_click) {
            if (JXUiHelper.getInstance().isUseCommonQuestion()){
                chatFragment.showCommonQuestionListWindows();
            }else {
                chatFragment.chatPresenter.fetchQuickQuestion();
            }
        } else if (drawableResId == R.drawable.jx_bg_advice){
            String url = JXUiHelper.getInstance().getSelfServiceOrderUrl();
            url = url + JXImManager.McsUser.getInstance().getSelfServiceParameter();
            startActivity(new Intent(JXChatUIActivity.this, JXWebViewActivity.class).putExtra(JXConstants
                    .EXTRA_WEBVIEW_URL, url));
        } else if (drawableResId == R.drawable.jx_bg_location_click) {
            chatFragment.startActivityForResult(new Intent(JXChatUIActivity.this, JXWebViewActivity.class)
//                    .putExtra(JXConstants.EXTRA_WEBVIEW_URL, "http://172.16.169.66:8190/webmcs/visitorSendGeolocation.html?app=true"),
                    .putExtra(JXConstants.EXTRA_WEBVIEW_URL, JXImManager.McsUser.getInstance().getLocationWebUrl())
                            .putExtra(JXConstants.EXTRA_GET_LOCATION,true),
                    JXChatView.LOCATION_REQUEST_CODE);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (chatFragment.onKeyDown(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onChatSession(boolean isWithRobot) {
        if(chatFragment != null){
            if(isWithRobot){
                List<Integer> robotFunction = new ArrayList<>();
                List<String> robotFunctionName = new ArrayList<>();
                robotFunction.add(R.drawable.jx_bg_quick_question_click);
                if (JXUiHelper.getInstance().isUseCommonQuestion()){
                    robotFunctionName.add(getString(R.string.jx_common_question));
                }else {
                    robotFunctionName.add(getString(R.string.jx_function_quick_question));
                }
                if (JXUiHelper.getInstance().sendImgToRobotEnable()){
                    robotFunction.add(R.drawable.jx_bg_image_click);
                    robotFunctionName.add(getString(R.string.jx_image));
                    robotFunction.add(R.drawable.jx_bg_take_photo_click);
                    robotFunctionName.add(getString(R.string.jx_take_photo));
                }
                if (JXImManager.Config.getInstance().robotSatisfyEnable()){
                    robotFunction.add(R.drawable.jx_bg_advice);
                    robotFunctionName.add(getString(R.string.jx_online_advice));
                }
                chatFragment.configFunctionPanel(robotFunction, robotFunctionName);
            }else{
                chatFragment.configFunctionPanel(functionImages, functionName);
            }
        }
    }

    private JXChatFragment messageBoxFragment =null;
    @Override
    public void onMessageBoxClick() {
        messageBoxFragment = new JXChatFragment();
        Bundle args = new Bundle();
        args.putInt(JXConstants.EXTRA_CHAT_TYPE, JXChatView.CHATTYPE_MESSAGE_BOX);
        args.putString(JXConstants.EXTRA_CHAT_TITLE_KEY, getString(R.string.jx_message_center));
        messageBoxFragment.setArguments(args);
        getSupportFragmentManager().beginTransaction().add(R.id.fl_container, messageBoxFragment, "messageBox")
        .addToBackStack("messageBox")
        .commit();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        JXChatFragment chatFragment = new JXChatFragment();
        Bundle args = new Bundle();
        // 设置相应属性,CHAT_KEY为聊天的对象,访客这里为技能组的ID，CHAT_SKILLS_DISPLAYNAME为技能组的昵称
        int chatType = intent.getIntExtra(JXConstants.EXTRA_CHAT_TYPE, JXChatView.CHATTYPE_CUSTOMER_SERVICE);
        if(chatType == JXChatView.CHATTYPE_MESSAGE_BOX){
            args.putInt(JXConstants.EXTRA_CHAT_TYPE, chatType);
            args.putString(JXConstants.EXTRA_CHAT_KEY, intent.getStringExtra(JXConstants.EXTRA_CHAT_KEY));
            args.putString(JXConstants.EXTRA_CHAT_TITLE_KEY, intent.getStringExtra(JXConstants.EXTRA_CHAT_TITLE_KEY));
            chatFragment.setArguments(args);
            FragmentManager fragmentManager = getSupportFragmentManager();
            Fragment fragment = fragmentManager.findFragmentByTag("messageBox");
            if(fragment != null){
                fragmentManager.popBackStackImmediate();
                fragmentManager.beginTransaction().remove(fragment).commit();
                getSupportFragmentManager().beginTransaction().add(R.id.fl_container, chatFragment, "messageBox")
                        .addToBackStack("messageBox")
                        .commit();
            }else{
                getSupportFragmentManager().beginTransaction().replace(R.id.fl_container, chatFragment, "messageBox")
                        .commit();
            }
        }else {
            reStart = true;
            reStartKey = intent.getStringExtra(JXConstants.EXTRA_CHAT_KEY);
            reStartSuboryId = intent.getStringExtra(JXConstants.EXTRA_SUBORG_ID_KEY);
            reStartTitleKey = intent.getStringExtra(JXConstants.EXTRA_CHAT_TITLE_KEY);
            finish();
        }
    }

    @Override
    public void onGranted() {
        if (permissionRequestCode == R.drawable.jx_bg_image_click){
            naviToSelectImage();
        }
        if (permissionRequestCode == R.drawable.jx_bg_take_photo_click){
            takePhoto();
        }
    }

    @Override
    public void onDenied() {
        if (permissionRequestCode == R.drawable.jx_bg_image_click){
            Toast.makeText(getApplicationContext(), getString(R.string.jx_storage_permission_denied), Toast.LENGTH_SHORT).show();
        }
        if (permissionRequestCode == R.drawable.jx_bg_take_photo_click){
            Toast.makeText(getApplicationContext(), getString(R.string.jx_camera_permission_denied), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        System.out.println("activity permission code  = "+requestCode);
        mJXPermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (chatFragment!= null){
            chatFragment.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    static class GetQuickQuestionTask extends AsyncTask<Boolean,Boolean,Boolean> {
        private WeakReference<JXChatUIActivity> weakAty;

        public GetQuickQuestionTask(JXChatUIActivity activity) {
            weakAty = new WeakReference<JXChatUIActivity>(activity);
        }

        @Override
        protected Boolean doInBackground(Boolean... params) {
            final List<String> quickQuestions = JXImManager.McsUser.getInstance().getQuickQuestions(JXUiHelper.getInstance().getSuborgId());
            if(isCancelled()){
                return false;
            }
            if (quickQuestions != null && quickQuestions.size()>0){
                return true;
            }else {
                return  false;
            }
        }

        @Override
        protected void onPostExecute(Boolean hasQuestions) {
            super.onPostExecute(hasQuestions);

            JXChatUIActivity activity = weakAty.get();
            if (activity == null
                    || activity.isFinishing()) {
                // activity没了,就结束可以了
                return;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                if (activity == null
                        || activity.isDestroyed()) {
                    // activity没了,就结束可以了
                    return;
                }
            }

            JXChatUIActivity mActivity;
            if ((mActivity = (JXChatUIActivity) weakAty.get()) != null) {
                if (hasQuestions){
                    mActivity.functionImages.add(R.drawable.jx_bg_quick_question_click);
                    mActivity.functionName.add(mActivity.getString(R.string.jx_function_quick_question));
                    mActivity.chatFragment.configFunctionPanel(mActivity.functionImages, mActivity.functionName);
                }
            }
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            Log.i("Mytask", "执行了取消");
        }
    }

    public void takePhoto(){
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                File dir = JXChatUIActivity.this.getExternalFilesDir(ImageMessage.EXTERNAL_FILES_DIR);
                if (!dir.exists()){
                    dir.mkdirs();
                }
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                chatFragment.cameraPhoto = new File(dir , System.currentTimeMillis() + ".jpg");
                Uri u;
                if (Build.VERSION.SDK_INT<=Build.VERSION_CODES.M){
                    u = Uri.fromFile(chatFragment.cameraPhoto);
                }else {
                    String providerAuth = getApplication().getPackageName()+".jxfileprovider";
                    u = FileProvider.getUriForFile(this, providerAuth,chatFragment.cameraPhoto);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                chatFragment.startActivityForResult(intent, JXChatView.GET_IMAGE_VIA_CAMERA);
            } catch (Exception e) {
                JXLog.e("[JXChatUIActivity.takePhoto] take photp exception ",e);
                Toast.makeText(JXChatUIActivity.this, getString(R.string.jx_storage_dir_not_found), Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(JXChatUIActivity.this, getString(R.string.jx_sdcard_not_found), Toast.LENGTH_LONG).show();
        }
    }

    public void naviToSelectImage(){
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra("return-data", true);
        chatFragment.startActivityForResult(intent, JXChatView.IMAGE_REQUEST_CODE);
    }
}
